<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------

namespace app\common\model;

use app\order\model\OrderGoods;
use think\Db;
use think\Model as ThinkModel;
use app\user\model\User as UserModel;
use app\user\model\Task as TaskModel;


/**
 * 购物车模型
 * @package app\operation\model
 */
class Order extends ThinkModel
{
     //表名
    protected $table = '__ORDER__';

    //主键
    protected $pk = 'order_sn';
    
    //自动写入时间
    protected $autoWriteTimestamp = true;

    // 设置当前模型对应的完整数据表名称
    public static $payTypes = [
        'wxpay' => '微信',
        'alipay' => '支付宝',
        'balance' => '余额支付',
        'minipay' => '微信小程序支付',
        'zero' => '零元支付',
    ];

    // 自动写入时间戳
    public static $orderTypes = [
        1 => '现金充值',
        2 => '虚拟币充值',
        3 => '商城交易',      
    ];

    public static $oeder_type_name = [
        1 => '',
        2 => '',
        3 => '普通商品',     
    ];
    //所有支付方式
    public static $pay_status = [
        0 => '未付款',
        1 => '已付款',
    ];
    //订单类型
    public static $order_status = [
        -2 => '取消中',
        -1 => '已取消',
        0 => '待支付',
        1 => '待发货',
        2 => '已发货',
        3 => '已完成',
        4 => '已评价',
        5 => '售后中',
        6 => '售后完成',
    ];

    //配送方式
    public static $sendTypeArr = [
        ['key' => 0, 'name' => '快递'],
        ['key' => 1, 'name' => '自提']
    ];

    public static function order_typeArr()
    {
        return [
            '3' => [ 'key' => 3,'name' => '普通订单' ]
        ];
    }



    /**
     * 创建充值订单
     * @param array $data 下单参数数组
     * @param array $user 会员数据数组
     * @return array
     * @throws \Exception
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public static function addRechargeOrder($data, $user)
    {
        $rule_id = $data['product_id'];
        if ($rule_id) {
            $rule = \app\user\model\RechargeRule::get($rule_id);
            if (!$rule) {
                throw new \Exception(lang('获取充值规则失败'));
            }
            $money = $rule['money'];
            if ($orderMoney = $data['order_money']) {
                if ($orderMoney != $money)
                    return frontReturn(0, "传递的金额{$orderMoney}与{$money}不一致");
            }
            $orderData['product_id'] = $data['product_id'];
        } else {
            $money = $data['order_money'];
        }

        if (!$money) {
            throw new \Exception(lang('缺少充值金额'));
        }

        //写入订单
        $order_no = get_order_sn('CZ');
        $orderData['user_id'] = $user['id'];
        $orderData['order_sn'] = $order_no;
        $orderData['order_money'] = $money;
        $orderData['payable_money'] = $data['payable_money'] ? $data['payable_money'] : $money;
        $orderData['real_money'] = 0;
        $orderData['pay_status'] = 0;
        $orderData['status'] = 0;
        $orderData['pay_type'] = $data['pay_type'];
        $orderData['order_type'] = $data['order_type'];
        $orderData['cost_price_total'] = 0;

        $ret = self::create($orderData);
        if (!$ret) {
            throw new \Exception(lang('创建订单失败'));
        }
        return [
            'order_sn' => $order_no
        ];
    }

    /**
     * 订单异步回调，支付回调
     * @param string $order_sn 订单号
     * @param int $pay_type 支付方式
     * @param string $transaction_id 第三方订单号
     * @return boolean
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */

    public static function verify($order_sn, $pay_type, $transaction_id = '', $total_fee)
    {
        $orderSn = $order_sn;
        set_time_limit(0);
        //加进程锁
        $locKey = "lock_" . $order_sn;
        $redis = \app\common\model\Redis::handler();
        $lock = $redis->get($locKey);
        if ($lock) {
            return false;
        }
        $order = self::where('order_sn', $order_sn)->find();
        if (!$order) {
            return false;
        }
        if ($order['pay_status'] > 0) {
            return true;
        }  
        $user = UserModel::get( $order['user_id']);
        $redis->setnx($locKey, 1);
        //使用事务
        Db::startTrans();
        try {
            $upOrder = [
                'pay_status' => 1,
                'pay_type' => $pay_type,
                'pay_time' => time(),
                'transaction_id' => $transaction_id,
            ];
            if ($order['order_type'] == 1 || $order['order_type'] == 2) {
                //如果是充值，则直接完成订单
                $upOrder['status'] = 3;
            } else {
                //商城订单改为已支付
                $upOrder['status'] = 1;
            }
            
            if ($pay_type == 'wxpay' || $pay_type == 'minipay' || $pay_type == 'minipay_mix') {
                $real_money = $total_fee / 100;
            } else {
                $real_money = $total_fee;
            }
            
            $upOrder['real_money'] = $real_money;   
            $res = self::where('order_sn',$order["order_sn"])->where("status","in",[-2,0])->update($upOrder);
            if (!$res) {
                exception(lang('订单处理异常'));
            }          
            // 更新消费总金额          
            UserModel::where("id",$order["user_id"])->setInc("total_consumption_money",$real_money);

           //处理子订单流程
            switch ($order['order_type']) {
                case 1:         
                    $remark = lang('现金充值订单');
                    if ($order['product_id']) {
                        $money = \app\user\model\RechargeRule::where('id', $order['product_id'])->value('add_money');
                    } else {
                        $money = $order['order_money'];
                    }

                    $after_money = \app\user\model\MoneyLog::changeMoney($user['id'], $user['user_money'], $money, 1, $remark, $order_sn);
                    if (!$after_money) {
                        exception(lang('订单处理异常'));
                    }
                    break;
                case 2:              
                    $remark = lang('虚拟币充值订单');
                    if ($order['product_id']) {
                        $money = \app\user\model\RechargeRule::where('id', $order['product_id'])->value('add_money');
                    } else {
                        $money = $order['order_money'];
                    }

                    $after_money = \app\user\model\VirtualMoneyLog::changeMoney($user['id'], $user['user_virtual_money'], $money, 1, $remark, $order_sn);
                    if (!$after_money) {
                        exception(lang('订单处理异常'));
                    }
                    break;
                case 3:
                    //商城订单
                    OrderGoods::verify($order,$user);  
                    break;
                default:
                    break;
            }          
            Db::commit();
        }
        //捕获抛出的异常
        catch (\Exception $e) {
            Db::rollback();     
            \think\facade\Log::error("OrderverifyError:" .$e->getMessage());
            exception($e->getMessage());
            return false;
        }
        //捕获语法。数据库语句级别异常
        catch (\Error $e) {
            Db::rollback();
            \think\facade\Log::error("OrderverifyError:" .$e->getMessage());
            exception($e->getMessage());
            return false;
        }
        //无论是否抛出异常，此处代码会保活
        finally{
           $redis->del($locKey);
        }
        TaskModel::doTask($order['user_id'], 'firstOrder');
        return true;
    }

}
